import React, { Component, useRef } from 'react'
import GoBack from '@/components/TheGoBack'
import { Form, Select, Input, Space, Button, Switch, Table } from 'antd'
import { SearchOutlined } from "@ant-design/icons";
import _ from 'lodash'
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheDialog from "@/components/TheDialog";
import { apiGetSheetDetailPage, apiGetSheetDetailActivePage, apiGetSheetDetailActiveAdd, apiGetSheetDetailActiveDel } from '@/request/coupons'

const SearchHeader = ({ openDialog, getValue }) => {
  const formRef = useRef()
  const options = [
    {
      value: 'J',
      label: '代金券'
    },
    {
      value: 'Z',
      label: '折扣券'
    },
    {
      value: 'D',
      label: '打车券'
    },
  ]
  const onFinish = (values) => {
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      couponTitle: '',
      prizeType: null
    })
    getValue({})
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between", marginTop: 20 }}
    >
      <Form ref={formRef} onFinish={onFinish} layout="inline">
        <Form.Item name="couponTitle">
          <Input suffix={<SearchOutlined />} placeholder={"请输入优惠券名称"} />
        </Form.Item>
        <Form.Item name="prizeType">
          <Select options={options} style={{ width: 140 }} placeholder={"优惠券类型"} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="submit" type="primary">搜索</Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <TheButton type="default" size="middle" onClick={openDialog}>
        添加优惠券
      </TheButton>
    </div>
  );
};

export default class AccessCoupons extends Component {
  state = {
    columns: [
      {
        title: "优惠券名称",
        dataIndex: "couponTitle",
        key: "couponTitle",
        render: (text, record) => {
          return <div className="p-white-space" style={{ width: 180 }}>{record.couponTitle}</div>
        }
      },
      {
        title: "优惠券类型",
        dataIndex: "prizeType",
        key: "prizeType",
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 'J':
              label = '代金券';
              break;
            case 'Z':
              label = '折扣券';
              break;
            case 'D':
              label = '打车券';
              break
            default:
              label = '--';
          }
          return label;
        }
      },
      {
        title: "优惠内容",
        dataIndex: "couponPrice",
        key: "couponPrice",
        render: (text, record) => {
          if (record.couponType === 'J') {
            return <React.$Price price={record.couponPrice} />
          }
          if (record.couponType === 'Z') {
            return `${React.$transNum(record.couponPrice, 1, -1)}折`
          }
          if (record.couponType === 'D') {
            return <React.$Price price={record.couponPrice} />
          }
        }
      },
      {
        title: "使用门槛",
        dataIndex: "usePrice",
        key: "usePrice",
        render: (text, record) => {
          if (record.usePrice === -1) {
            return <div>无条件限制</div>
          } else {
            return `满${React.$transNum(record.usePrice, 2, -2)}可用`
          }
        }
      },
      {
        title: "使用期限",
        render: (text, record) => {
          if (record.timeType === 1) {
            return <div>{record.effectiveTime}天</div>
          }else{
            return <div>{`${record.startTime}`} 至 {`${record.endTime}`}</div>
          }
        }
      },
      {
        title: "剩余张数",
        dataIndex: "couponStock",
        key: "couponStock",
        render: (text, record) => {
          if (parseInt(record.couponStock) === -1) {
            return '无限量'
          } else {
            return record.couponStock
          }
        }
      },
      {
        title: '操作',
        render: (text, record) => {
          return <TheButton onClick={() => this.delConfirm(record)}>移除</TheButton>
        }
      }
    ],
    couponsColumns: [
      {
        title: "优惠券名称",
        dataIndex: "couponTitle",
        key: "couponTitle",
        width: 180,
        render: (text, record) => {
          return <div className="p-white-space" style={{ width: 140 }}>{record.couponTitle}</div>
        }
      },
      {
        title: "优惠券类型",
        dataIndex: "couponType",
        key: "couponType",
        width: 180,
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 'J':
              label = '代金券';
              break;
            case 'Z':
              label = '折扣券';
              break;
            case 'D':
              label = '打车券';
              break;
            default:
              label = '--';
          }
          return label;
        }
      },
      {
        title: "优惠内容",
        dataIndex: "couponPrice",
        key: "couponPrice",
        render: (text, record) => {
          if (record.couponType === 'J') {
            return <React.$Price price={record.couponPrice} />
          }
          if (record.couponType === 'Z') {
            return `${React.$transNum(record.couponPrice, 1, -1)}折`
          }
          if (record.couponType === 'D') {
            return <React.$Price price={record.couponPrice} />
          }
        }
      },
      {
        title: "使用门槛",
        dataIndex: "usePrice",
        key: "usePrice",
        render: (text, record) => {
          if (record.usePrice === -1) {
            return <div>无条件限制</div>
          } else {
            return `满${React.$transNum(record.usePrice, 2, -2)}可用`
          }
        }
      },
      {
        title: "使用期限",
        render: (text, record) => {
          if (record.timeType === 1) {
            return <div>{record.effectiveTime}天</div>
          }else{
            return <div>{`${record.startTime}`} 至 {`${record.endTime}`}</div>
          }
        }
      },
      {
        title: "剩余张数",
        dataIndex: "couponStock",
        key: "couponStock",
        render: (text, record) => {
          if (parseInt(text) === -1) {
            return '无限量'
          } else {
            return parseInt(text).toLocaleString()
          }
        }
      },
    ],
    dataSource: [],
    couponsData: [],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    couponsPage: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    couponsTotal: 0,
    loading: false,
    couponsLoading: false,
    btnLoading: false,
    selectedRowKeys: [],
    visible: false
  }
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    const { pageData, searchValue } = this.state
    const { id } = this.props.match.params
    let res = await apiGetSheetDetailPage({ ...pageData, ...searchValue, activityId: id })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data
      })
    }
  }
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  }
  delConfirm = (value) => {
    const { couponId, activityId } = value
    React.$confirm({
      title: `您确定移除此优惠券吗？`,
      onOk: async () => {
        let res = await apiGetSheetDetailActiveDel({ activityId, couponId, status: 1 })
        if (res.code === 0) {
          await React.$message({
            type: 'info',
            content: '移除成功'
          })
          this.getData()
        }
      }
    })
  }
  openDialog = async () => {
    await this.getCouponsPage()
    this.setState({
      visible: true
    })
  }
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys })
  };
  getCouponsPage = async () => {
    const { id } = this.props.match.params
    const { couponsPage } = this.state
    let res = await apiGetSheetDetailActivePage({ activityId: id, ...couponsPage })
    this.setState({
      couponsData: res.data.map(v => {
        return {
          ...v,
          key: v.couponId
        }
      })
    })
  }
  couponsPageChange = (pageNo, pageSize) => {
    this.setState({
      couponsPage: {
        pageNo,
        pageSize
      }
    }, () => this.getCouponsPage())
  }
  handleOk = async () => {
    const { selectedRowKeys } = this.state
    const { id } = this.props.match.params
    this.setState({
      loading: true
    })
    let res = await apiGetSheetDetailActiveAdd({
      couponInfos: selectedRowKeys,
      activityId: id
    })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '添加优惠券成功'
      })
    }
    this.setState({
      selectedRowKeys: [],
      loading: false,
      visible: false
    }, () => this.getData())
  }
  handleCancel = () => {
    this.setState({
      selectedRowKeys: [],
      loading: false,
      visible: false
    })
  }
  render() {
    const { columns, dataSource, pageData: { pageNo, pageSize }, total, loading, couponsColumns, couponsData, visible, selectedRowKeys, couponsPage, couponsTotal } = this.state
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className="p-layout-box">
        <GoBack history={this.props.history} title="查看优惠券" />
        <SearchHeader openDialog={this.openDialog} getValue={this.getValue} />
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} loading={loading} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>
        <TheDialog
          width={1200}
          title={'添加优惠券'}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <div style={{ marginBottom: -30 }}>
            <Table
              bordered
              rowSelection={rowSelection}
              columns={couponsColumns}
              dataSource={couponsData}
              pagination={false}
              scroll={{ x: 'max-content', y: '30vh' }}
            />
            <ThePagination pageNo={couponsPage.pageNo} pageSize={couponsPage.pageSize} total={couponsTotal} pageChange={this.couponsPageChange} />
          </div>
        </TheDialog>
      </div>
    )
  }
}
